package com.xhs.service;

import com.xhs.model.User;
import com.xhs.manager.UserManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户服务
 * 处理用户相关的业务逻辑，包括Cookie转换和用户信息管理
 *
 * @author xhs
 */
@Slf4j
@Service
public class UserService {

    @Autowired
    private UserManager userManager;

    /**
     * 将Cookie数组转换为浏览器可直接使用的字符串格式
     * 
     * @param cookies Cookie数组
     * @return Cookie字符串，格式：name1=value1; name2=value2; name3=value3
     */
    public String convertCookiesToString(List<Map<String, Object>> cookies) {
        if (cookies == null || cookies.isEmpty()) {
            log.warn("Cookie数组为空，返回空字符串");
            return "";
        }

        String cookieString = cookies.stream()
                .filter(cookie -> cookie.containsKey("name") && cookie.containsKey("value"))
                .map(cookie -> {
                    String name = String.valueOf(cookie.get("name"));
                    String value = String.valueOf(cookie.get("value"));
                    return name + "=" + value;
                })
                .collect(Collectors.joining("; "));

        log.info("Cookie转换完成: cookieCount={}, stringLength={}", cookies.size(), cookieString.length());
        log.debug("Cookie字符串前200字符: {}", cookieString.substring(0, Math.min(200, cookieString.length())));
        
        return cookieString;
    }

    /**
     * 获取用户Cookie字符串
     *
     * @param phoneNumber 手机号
     * @return Cookie字符串
     */
    public String getCookie(String phoneNumber) {
        return userManager.getCookie(phoneNumber);
    }

    /**
     * 删除用户Cookie
     *
     * @param phoneNumber 手机号
     * @return 是否成功
     */
    public boolean deleteCookie(String phoneNumber) {
        return userManager.deleteCookie(phoneNumber);
    }

    /**
     * 检查用户是否有Cookie
     *
     * @param phoneNumber 手机号
     * @return 是否存在Cookie
     */
    public boolean hasCookie(String phoneNumber) {
        return userManager.hasCookie(phoneNumber);
    }

    /**
     * 用户登录处理（包含Cookie保存）
     *
     * @param phoneNumber 手机号
     * @param cookies Cookie数组
     * @return 用户信息
     */
    public User loginWithCookies(String phoneNumber, List<Map<String, Object>> cookies) {
        String cookieString = convertCookiesToString(cookies);
        return userManager.saveOrUpdateUserLogin(phoneNumber, cookieString);
    }

}